import {
  Component,
  Input,
  Output,
  EventEmitter,
  OnInit,
  OnDestroy
} from '@angular/core';
import { fromEvent, Subscription } from 'rxjs';
import {
  trigger,
  style,
  animate,
  transition
} from '@angular/animations';

@Component({
  selector: 'app-network-status',
  templateUrl: './network-status.component.html',
  styleUrls: ['./network-status.component.scss'],
  animations: [
    trigger('fadeSlide', [
      transition(':enter', [
        style({ transform: 'translateY(-100%)', opacity: 0 }),
        animate('0.3s ease', style({ transform: 'translateY(0)', opacity: 1 }))
      ]),
      transition(':leave', [
        animate('0.3s ease', style({ transform: 'translateY(-100%)', opacity: 0 }))
      ])
    ])
  ]
})
export class NetworkStatusComponent implements OnInit, OnDestroy {
  @Input() retryable = true;
  @Input() customMessage = '';
  @Output() networkChange = new EventEmitter<boolean>();

  isOnline = navigator.onLine;
  retrying = false;

  private onlineSub!: Subscription;
  private offlineSub!: Subscription;

  get message(): string {
    if (this.retrying) {
      return '正在重新连接...';
    }
    return (
      this.customMessage ||
      (this.isOnline ? '网络已连接' : '网络连接已断开')
    );
  }

  ngOnInit(): void {
    this.onlineSub = fromEvent(window, 'online').subscribe(() =>
      this.updateStatus(true)
    );
    this.offlineSub = fromEvent(window, 'offline').subscribe(() =>
      this.updateStatus(false)
    );
  }

  ngOnDestroy(): void {
    this.onlineSub.unsubscribe();
    this.offlineSub.unsubscribe();
  }

  private updateStatus(status: boolean): void {
    this.isOnline = status;
    this.networkChange.emit(status);
  }

  async handleRetry(): Promise<void> {
    this.retrying = true;
    try {
      await fetch(`${window.location.origin}/ping`);
      this.isOnline = true;
    } catch (err) {
      console.error('Network retry failed:', err);
    } finally {
      this.retrying = false;
    }
  }
}
